package com.test.myestest.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class ESUtil {
    /**
     * multipartFile转base64
     * @param multipartFile multipartFile
     * @return result
     * @throws Exception e
     */
    public static String multipartFileToBase64(MultipartFile multipartFile) throws Exception {
        // 检查文件是否为空
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 获取文件字节数组
        byte[] fileBytes = multipartFile.getBytes();

        // 使用 Base64 编码
        return Base64.getEncoder().encodeToString(fileBytes);
    }

    /**
     * 文件下载地址转base64
     * @param path 下载地址
     * @return result
     * @throws IOException e
     */
    public static String pdfToBase64(String path) throws IOException {
        InputStream is;
        URL url2 = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1000];
            int rc;
            while ((rc = is.read(buff, 0, 1000)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new BASE64Encoder().encode(data).replace("\n", "").replace("\r", "");
    }
}
